/* USER CODE BEGIN Header */
/**
  ******************************************************************************
  * @file           : main.c
  * @brief          : Main program body
  ******************************************************************************
  * @attention
  *
  * Copyright (c) 2025 STMicroelectronics.
  * All rights reserved.
  *
  * This software is licensed under terms that can be found in the LICENSE file
  * in the root directory of this software component.
  * If no LICENSE file comes with this software, it is provided AS-IS.
  *
  ******************************************************************************
  */
/* USER CODE END Header */
/* Includes ------------------------------------------------------------------*/
#include "main.h"
#include "adc.h"
#include "dac.h"
#include "dma.h"
#include "hrtim.h"
#include "tim.h"
#include "usart.h"
#include "gpio.h"

/* Private includes ----------------------------------------------------------*/
/* USER CODE BEGIN Includes */
#include "oled.h"
#include "bmp.h"
#include "stdio.h"
/* USER CODE END Includes */

/* Private typedef -----------------------------------------------------------*/
/* USER CODE BEGIN PTD */
#define HTIMFREQ 1024000//HRTIM��ʱ��Ƶ��
/* USER CODE END PTD */

/* Private define ------------------------------------------------------------*/
/* USER CODE BEGIN PD */

/* USER CODE END PD */

/* Private macro -------------------------------------------------------------*/
/* USER CODE BEGIN PM */

/* USER CODE END PM */

/* Private variables ---------------------------------------------------------*/

/* USER CODE BEGIN PV */

/* USER CODE END PV */

/* Private function prototypes -----------------------------------------------*/
void SystemClock_Config(void);
/* USER CODE BEGIN PFP */
uint16_t ADC_Data[30];
uint8_t uart_rev[25];
SysTypeDef Sys;


/* USER CODE END PFP */

/* Private user code ---------------------------------------------------------*/
/* USER CODE BEGIN 0 */
uint16_t PER;
void FreqSet(float Freq)  //ferq ��λkhz
{
	//PW频率=HRTIM频率/PER	
	//sTimerxRegs[0]---->TimerA
	//sTimerxRegs[1]---->TimerB
	//sTimerxRegs[2]---->TimerC
	//sTimerxRegs[3]---->TimerD
	//sTimerxRegs[4]---->TimerE
	PER= (double)HTIMFREQ/Freq;
	hhrtim1.Instance->sTimerxRegs[3].PERxR = PER;
	hhrtim1.Instance->sTimerxRegs[3].CMP1xR = PER/2;
}

void XrayStart(uint16_t time,uint16_t KV,uint16_t mA)
{
  Sys.SetKvtime=time;
	Sys.SetKV= KV;
	Sys.SetMa= mA;
  FreqSet(115.0);
	HAL_HRTIM_WaveformCountStart(&hhrtim1, HRTIM_TIMERID_TIMER_D);
  HAL_HRTIM_WaveformOutputStart(&hhrtim1, HRTIM_OUTPUT_TD1);
  HAL_HRTIM_WaveformOutputStart(&hhrtim1, HRTIM_OUTPUT_TD2);
	HAL_TIM_Base_Start_IT(&htim2);
}

void XrayStop(void)
{
	Sys.KvTime=0;
  HAL_HRTIM_WaveformCountStop(&hhrtim1, HRTIM_TIMERID_TIMER_D);
  HAL_HRTIM_WaveformOutputStop(&hhrtim1, HRTIM_OUTPUT_TD1);
  HAL_HRTIM_WaveformOutputStop(&hhrtim1, HRTIM_OUTPUT_TD2);
	HAL_TIM_Base_Stop_IT(&htim2);	
	HAL_GPIO_WritePin(BUZZER_GPIO_Port,BUZZER_Pin,0);
}

void LightVolteSet(uint16_t volte)
{
	uint16_t DacValue;
  DacValue=(float)volte/10.0/3.3*4095*0.66;
	HAL_DAC_SetValue(&hdac1, DAC_CHANNEL_1, DAC_ALIGN_12B_R, (uint16_t)DacValue);
}

void CheckHighVolte(void)
{
   Sys.BAT=((float)ADC_Data[2]/4095.0*3.3)*22.2766*1.321;
	 Sys.Kvfb= (float)ADC_Data[0]/4095.0*3.3*100;
	 Sys.Mafb= (float)ADC_Data[1]/4095.0*3.3;
    // printf("Kv is %.2f %.2fKv\r\nMa is %.2f\r\n",KV,(float)KV*330000000.0/100000.0/1000.0*13.0*1.414,MA);
}







//void ui_update(void)
//{
//     OLED_ShowNum(60,17,(uint16_t)Freq,3,16,1);
//     OLED_ShowString(84,17,(uint8_t*)".",16,1);
//     OLED_ShowNum(90,17,10*(Freq-(uint16_t)Freq),1,16,1);
//		 OLED_ShowNum(30,50,uart_rev[0],2,8,1);
//		 OLED_ShowNum(47,50,uart_rev[1],2,8,1);
//		 OLED_ShowNum(64,50,uart_rev[2],2,8,1);
//		 OLED_ShowNum(81,50,uart_rev[3],2,8,1);
//		 OLED_ShowNum(98,50,uart_rev[4],2,8,1);
//		 OLED_ShowNum(115,50,uart_rev[5],2,8,1);
//     OLED_Refresh();
//}

void Sys_init(void)
{
  HAL_UARTEx_ReceiveToIdle_IT(&huart3,uart_rev,20);	
  HAL_DAC_Start(&hdac1,DAC1_CHANNEL_1);
	HAL_GPIO_WritePin(MD0_GPIO_Port,MD0_Pin,1);
	HAL_GPIO_WritePin(MD1_GPIO_Port,MD1_Pin,0);
	//HAL_ADC_Start(&hadc1);
	HAL_Delay(10);
	HAL_ADC_Start_DMA(&hadc1,(uint32_t*)ADC_Data,30);
}

/* USER CODE END 0 */

/**
  * @brief  The application entry point.
  * @retval int
  */
int main(void)
{

  /* USER CODE BEGIN 1 */
  uint16_t i;
  /* USER CODE END 1 */

  /* MCU Configuration--------------------------------------------------------*/

  /* Reset of all peripherals, Initializes the Flash interface and the Systick. */
  HAL_Init();

  /* USER CODE BEGIN Init */

  /* USER CODE END Init */

  /* Configure the system clock */
  SystemClock_Config();

  /* USER CODE BEGIN SysInit */

  /* USER CODE END SysInit */

  /* Initialize all configured peripherals */
  MX_GPIO_Init();
  MX_DMA_Init();
  MX_USART1_UART_Init();
  MX_USART2_UART_Init();
  MX_USART3_UART_Init();
  MX_DAC1_Init();
  MX_HRTIM1_Init();
  MX_TIM2_Init();
  MX_ADC1_Init();
  /* USER CODE BEGIN 2 */
	OLED_Init();
	Sys_init();
  //OLED_ShowBootScreen();
	OLED_ShowBootScreen();
	HAL_Delay(3000);
  OLED_Clear();
	//OLED_TestBoundary();
  //HAL_TIM_Base_Start_IT(&htim2);
  /* USER CODE END 2 */

  /* Infinite loop */
  /* USER CODE BEGIN WHILE */
  while (1)
  {
		
		switch (Sys.Xray)
		{
			case 0:OLED_ShowReadyScreen(Sys.BAT,160,500,500); break;
			case 1:OLED_ShowRadiationScreen(Sys.PRS,Sys.MOSTmp,Sys.Mafb,Sys.Kvfb);break;
			default: OLED_Clear();
		}
		
		CheckHighVolte();
	  HAL_Delay(500);
    /* USER CODE END WHILE */

    /* USER CODE BEGIN 3 */
  }
  /* USER CODE END 3 */
}

/**
  * @brief System Clock Configuration
  * @retval None
  */
void SystemClock_Config(void)
{
  RCC_OscInitTypeDef RCC_OscInitStruct = {0};
  RCC_ClkInitTypeDef RCC_ClkInitStruct = {0};
  RCC_PeriphCLKInitTypeDef PeriphClkInit = {0};

  /** Initializes the RCC Oscillators according to the specified parameters
  * in the RCC_OscInitTypeDef structure.
  */
  RCC_OscInitStruct.OscillatorType = RCC_OSCILLATORTYPE_HSI;
  RCC_OscInitStruct.HSIState = RCC_HSI_ON;
  RCC_OscInitStruct.HSICalibrationValue = RCC_HSICALIBRATION_DEFAULT;
  RCC_OscInitStruct.PLL.PLLState = RCC_PLL_ON;
  RCC_OscInitStruct.PLL.PLLSource = RCC_PLLSOURCE_HSI;
  RCC_OscInitStruct.PLL.PLLMUL = RCC_PLL_MUL16;
  if (HAL_RCC_OscConfig(&RCC_OscInitStruct) != HAL_OK)
  {
    Error_Handler();
  }

  /** Initializes the CPU, AHB and APB buses clocks
  */
  RCC_ClkInitStruct.ClockType = RCC_CLOCKTYPE_HCLK|RCC_CLOCKTYPE_SYSCLK
                              |RCC_CLOCKTYPE_PCLK1|RCC_CLOCKTYPE_PCLK2;
  RCC_ClkInitStruct.SYSCLKSource = RCC_SYSCLKSOURCE_PLLCLK;
  RCC_ClkInitStruct.AHBCLKDivider = RCC_SYSCLK_DIV1;
  RCC_ClkInitStruct.APB1CLKDivider = RCC_HCLK_DIV2;
  RCC_ClkInitStruct.APB2CLKDivider = RCC_HCLK_DIV1;

  if (HAL_RCC_ClockConfig(&RCC_ClkInitStruct, FLASH_LATENCY_2) != HAL_OK)
  {
    Error_Handler();
  }
  PeriphClkInit.PeriphClockSelection = RCC_PERIPHCLK_HRTIM1|RCC_PERIPHCLK_USART1
                              |RCC_PERIPHCLK_ADC12;
  PeriphClkInit.Usart1ClockSelection = RCC_USART1CLKSOURCE_PCLK1;
  PeriphClkInit.Adc12ClockSelection = RCC_ADC12PLLCLK_DIV1;
  PeriphClkInit.Hrtim1ClockSelection = RCC_HRTIM1CLK_PLLCLK;
  if (HAL_RCCEx_PeriphCLKConfig(&PeriphClkInit) != HAL_OK)
  {
    Error_Handler();
  }
}

/* USER CODE BEGIN 4 */
uint16_t test1;
void HAL_TIM_PeriodElapsedCallback(TIM_HandleTypeDef *htim)  //1ms时基
{
	static float Freq;
    /* 检查是否是定时器 TIM2 的中断 */
    if (htim->Instance == TIM2)
    {
			 Sys.KvTime++;			 
			
			 if (Sys.KvTime%1000==0)
			 {
				 HAL_GPIO_TogglePin(BUZZER_GPIO_Port,BUZZER_Pin);
			 }
			 
			 if(Freq>SetFreq&&Kvflag==0&&Freq>70)
			 {
				 Freq-=0.001;
				 FreqSet(Freq);
			 }
			 if (Sys.KvTime>Sys.SetKvtime*10000)
			 {
			    XrayStop();
			 }
			 

        /* 在这里添加你的代码 */
    }
 

}

void HAL_UARTEx_RxEventCallback(UART_HandleTypeDef *huart, uint16_t Size)
{
   if (huart->Instance == USART3)
    {
         HAL_UARTEx_ReceiveToIdle_IT(&huart3,uart_rev,20);
			   if(uart_rev[0]==0xaa&&uart_rev[5]==0x5a&&Size==6)
				 {
					 //SetFreq=(float)(uart_rev[1]<<8|uart_rev[2])/10.0;
					 //LightSet=uart_rev[3];
					 if(uart_rev[4]==1)
					 {
              //XrayStart(8);
						  //printf("XRay,Freq%.2f!!!!!!!!!!!!!!!!!!!!!!!!!\r\n",SetFreq);
					 }
					 else 
					 {
              XrayStop();
						  printf("XrayStop-----------------------\r\n");
					 }
			     printf("\r\n\r\nset ok####################################\r\n\r\n");
				 }
    }
	 
}

/* USER CODE END 4 */

/**
  * @brief  This function is executed in case of error occurrence.
  * @retval None
  */
void Error_Handler(void)
{
  /* USER CODE BEGIN Error_Handler_Debug */
  /* User can add his own implementation to report the HAL error return state */
  __disable_irq();
  while (1)
  {
  }
  /* USER CODE END Error_Handler_Debug */
}

#ifdef  USE_FULL_ASSERT
/**
  * @brief  Reports the name of the source file and the source line number
  *         where the assert_param error has occurred.
  * @param  file: pointer to the source file name
  * @param  line: assert_param error line source number
  * @retval None
  */
void assert_failed(uint8_t *file, uint32_t line)
{
  /* USER CODE BEGIN 6 */
  /* User can add his own implementation to report the file name and line number,
     ex: printf("Wrong parameters value: file %s on line %d\r\n", file, line) */
  /* USER CODE END 6 */
}
#endif /* USE_FULL_ASSERT */
